import * as monaco from "monaco-editor";
import { ref } from "vue";
import { initializeMonacoWorkers } from "../utils/monaco-workers";

// 初始化 Monaco 编辑器的 workers
initializeMonacoWorkers();

export function useEditor() {
  const editor = ref(null);
  let currentModel = null;

  const initEditor = () => {
    if (editor.value) return;

    const editorElement = document.getElementById("editor");
    if (!editorElement) {
      console.error("Editor element not found");
      return;
    }

    editor.value = monaco.editor.create(editorElement, {
      theme: "vs-dark",
      fontSize: 14,
      minimap: { enabled: true },
      automaticLayout: true,
      scrollBeyondLastLine: false,
      lineNumbers: "on",
      roundedSelection: false,
      scrollbar: {
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        vertical: "visible",
        horizontal: "visible",
      },
    });
  };

  const disposeEditor = () => {
    if (currentModel) {
      currentModel.dispose();
      currentModel = null;
    }
    if (editor.value) {
      editor.value.dispose();
      editor.value = null;
    }
  };

  const updateEditorContent = (content, language) => {
    if (!editor.value) return;

    if (currentModel) {
      currentModel.dispose();
    }

    currentModel = monaco.editor.createModel(content, language);
    editor.value.setModel(currentModel);
  };

  return {
    editor,
    initEditor,
    disposeEditor,
    updateEditorContent,
  };
}
